﻿namespace WLFramework.Validation
{
    using System;
    using WLFramework.Validation;

    [AttributeUsage(AttributeTargets.Property)]
    public class CustomRegularAttribute : ValidateBaseAttribute
    {
        public string RegexText { get; set; }

        public CustomRegularAttribute(string regex)
            :this(regex, null, null)
        { 
        }

        public CustomRegularAttribute(string regex, string errorMessage)
            : this(regex, errorMessage, "请输入{0}")
        {
        }

        public CustomRegularAttribute(string regex, string errorMessage, string helpMessage)
            : base(errorMessage ?? "{0} 不符合格式要求", helpMessage ?? "{0} 必须满足格式要求")
        {
            this.RegexText = regex;
        }
        
        public override ValidateResult IsValid(ValidationContext context)
        {
            return RegexValidation.IsCustom(context.Value.ToString(), this.RegexText) ?
                ValidateResult.Success :
                new ValidateResult(string.Format(this.ErrorMessage, context.DisplayName));
        }
    }
}
